package controller;

import model.Log;
import model.LogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-07
 * Time：22:36
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || password == null || username.isEmpty() || password.isEmpty()){
            resp.getWriter().write("您的用户名或密码为空！");
        }
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if (user == null) {
            resp.getWriter().write("你输入的用户名或密码错误！");
            return;
        }
        if (!user.getPassword().equals(password)) {
            resp.getWriter().write("你输入的用户名或密码错误！");
            return;
        }
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        resp.sendRedirect("blog_list.html");

        //输出日志
        Log log = new Log();
        log.setUserId(user.getUserId());
        log.setAction("该用户登陆博客系统成功！");
        LogDao logDao = new LogDao();
        logDao.insert(log);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setStatus(403);
            return;
        }

        if (session.getAttribute("user") == null) {
            resp.setStatus(403);
            return;
        }
        resp.setStatus(200);
    }
}
